import React, {Component} from "react";
import {Route, Redirect,} from 'react-router-dom'

import NotFound from '../../containers/404'

class Auth extends Component {

    switchRouter = (path, pathtarget) => {
       if (path === pathtarget) return true
       const reg = new RegExp(`(^${path})(?=/)`)
       return reg.test(pathtarget)
    }
    render() {
        const {location, router} = this.props
        const { pathname } = location
        const token = sessionStorage.getItem('token')
        const targetRouter = router.find((v) => {
            return this.switchRouter(v.path, pathname)
        })
        if (!targetRouter) {
           return  <NotFound></NotFound>
        }else {
            if (token) {
                return <LoginHandle targetRouterConfig={targetRouter}></LoginHandle>
            } else {
                return <NotLogin targetRouterConfig={targetRouter}></NotLogin>
            }  
        }
       
  }
}

// 未登录状态
const NotLogin = (props) => {
   const {targetRouterConfig} = props
   const {auth } = targetRouterConfig
   if (auth) {
       return <Redirect to="/login"></Redirect>
   } else {
       return <Route path={targetRouterConfig.path} render={props => (
           <targetRouterConfig.component {...props} childrenRoute={targetRouterConfig.targetRouterConfig}></targetRouterConfig.component>
       )}></Route>
   }
}

const LoginHandle = (props) => {
    const {targetRouterConfig} = props
    const {path } = targetRouterConfig
    if (path  === '/login') {
        return <Redirect to="/home/user"></Redirect>
    } else {
        return <Route path={targetRouterConfig.path} render={props => (
            <targetRouterConfig.component {...props} childrenRoute={targetRouterConfig.childrenRoute}></targetRouterConfig.component>
        )}></Route>
    }
}

export default Auth;